package com.dougs.timehandler;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import com.dougs.timehandler.databinding.FragmentLockCounterBinding;

public class LockCounterFragment extends Fragment {

    private FragmentLockCounterBinding binding;
    private CountDownTimer countDownTimer;

    @Override
    public View onCreateView(
            @NonNull LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState
    ) {
        binding = FragmentLockCounterBinding.inflate(inflater, container, false);
        return binding.getRoot();
    }

    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        int milSecond = 0;
        if (getArguments() != null) {
            int minute = getArguments().getInt("lockTime");
            milSecond = minute * 60 * 1000;
//            milSecond = minute * 1000;
        }

        //动态倒计时，每秒更新一次
        countDownTimer = new CountDownTimer(milSecond, 1000) {
            public void onTick(long millisUntilFinished) {
                long second = millisUntilFinished / 1000;
                long minute = second / 60;
                long hour = 0;
                second = second % 60;
                if(minute > 59){
                    hour = minute / 60;
                    minute = minute % 60;
                }

                String leftTime = getResources().getString(R.string.left_time);
                String realTime = String.format(leftTime, minute, second);
                if(hour > 0){
                    leftTime = "%d小时"+leftTime;
                    realTime = String.format(leftTime, hour, minute, second);
                }

                binding.textviewLeftTime.setText(realTime);
            }

            public void onFinish() {
                Log.i("Timer", "onFinish: 倒计时结束");
                binding.textviewLeftTime.setText("时间到，休息一下~_~");
            }
        }.start();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
        // 停止倒计时，如果Fragment销毁，确保取消倒计时，避免内存泄漏
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
    }

}